<?php
class M_Work extends MVC_Model_Base {

    public function getAllSteps () {
        $objDbReader = $this->getDbReader('MAIN', 'work_steps');
        return $objDbReader->msql('');
    }


    /**
     * Данный метод работает при условии, что исполнитель находится не более чем
     * в 3-рех группах.
     *
     * TODO, подумать над нормальной реализацией
     */
    public function getStepsColors () {
        $sqlGetColors = <<<SQL
SELECT
s.*,
(SELECT color FROM work_groups WHERE id = IF(s.is_ok = 0, IF(COUNT(*) > 3, MIN(g.id), MAX(g.id)), 6)) as color
FROM work_executors as e
INNER JOIN work_executors_groups as eg
ON e.id = eg.executor_id
INNER JOIN work_groups as g
ON g.id = eg.group_id
INNER JOIN work_executors_steps as es
ON e.id = es.executor_id
INNER JOIN work_steps as s
ON s.id = es.step_id
GROUP BY s.id
SQL;
        $db = $this->getDb('MAIN');

        return $db->select($sqlGetColors);
    }


    public function getLegend () {
        $sqlGetLegend = <<<SQL
SELECT color as ARRAY_KEY_1, e.id as ARRAY_KEY_2, fio
FROM work_executors as e
INNER JOIN work_executors_groups as eg
ON e.id = eg.executor_id
INNER JOIN work_groups as g
ON g.id = eg.group_id
SQL;

        return $this->getDb('MAIN')->select($sqlGetLegend);
    }


    public function setStepOk ($step_id) {
        $sqlSetOk = <<<SQL
UPDATE work_steps SET is_ok = 1 WHERE id = ?
SQL;
        $this->getDb('MAIN')->query($sqlSetOk, $step_id);
    }


    public function setStepWork ($step_id) {
        $sqlSetOk = <<<SQL
UPDATE work_steps SET is_ok = 0 WHERE id = ?
SQL;
        $this->getDb('MAIN')->query($sqlSetOk, $step_id);
    }

}